package nl.utwente.csc.obsl.transformation.alloy2textwithexamples;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import nl.utwente.csc.obsl.transformation.alloy2textwithexamples.main.GenerateAlloySpec;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.util.BasicMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.progress.IProgressService;

public class Alloy2TextHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		ISelection sel = HandlerUtil.getActiveMenuSelection(event);
		IStructuredSelection selection = (IStructuredSelection) sel;
		final Object firstElement = selection.getFirstElement();
		final IFile sourceFile = (IFile) firstElement;
		IProgressService progressService = PlatformUI.getWorkbench()
				.getProgressService();
		try {
			progressService.busyCursorWhile(new IRunnableWithProgress() {
				public void run(IProgressMonitor monitor) {

					File target = sourceFile.getParent().getLocation().toFile();
					GenerateAlloySpec generator;
					try {
						generator = new GenerateAlloySpec(
								URI.createFileURI(sourceFile.getLocation().toString()),
								target,
								new ArrayList<String>());
					generator.doGenerate(BasicMonitor.toMonitor(monitor));
					System.out.println("TARGET: "+ target.getAbsolutePath());
					sourceFile.getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor);
					} catch (IOException | CoreException e) {
						IStatus status = new Status(IStatus.ERROR,
								Activator.PLUGIN_ID, e.getMessage(), e);
						Activator.getDefault().getLog().log(status);
					}				}
			});
		} catch (Exception e) {
			IStatus status = new Status(IStatus.ERROR,
					Activator.PLUGIN_ID, e.getMessage(), e);
			Activator.getDefault().getLog().log(status);
		}
		return null;
	}

}
